const { readFileSync } = require('fs');
const https = require('https');
const path = require('path');

const fs = require('fs');

// 将两个证书文件读取放到options对象中
// 使用readFileSync()方法，顺序地执行读文件和启动服务操作
const options = {
	key: fs.readFileSync(path.resolve(__dirname, '../ssl/localhost+3-key.pem')),
	cert: fs.readFileSync(path.resolve(__dirname, '../ssl/localhost+3.pem')),
};

const server = https.createServer(options);

server.listen(3001, () =>
	console.log('服务器开启了，点击访问：https://127.0.0.1:3001')
);

server.on('request', (request, response) => {
	const routeList = [setCors, setSessionId, getHomePage];

	for (const route of routeList) {
		let nextFlag = false;

		route(request, response, () => {
			nextFlag = true;
		});

		if (!nextFlag) {
			return;
		}
	}

	response.end('not Found');
});

// 获取首页的路由
function getHomePage(request, response, next) {
	if (request.url !== '/') {
		next();
		return;
	}

	response.end(readFileSync('./index.html', 'utf-8'));
	return;
}

// cors设置
function setCors(request, response, next) {
	response.setHeader('Content-Type', 'text/html;charset=utf-8');
	response.setHeader('Access-Control-Allow-Origin', 'https://127.0.0.1:3001');
	response.setHeader(
		'Access-Control-Allow-Methods',
		'GET, POST, PUT, DELETE, OPTIONS'
	);
	response.setHeader('Access-Control-Allow-Headers', '*');
	response.setHeader('Access-Control-Allow-Credentials', 'true');

	next();
}

// 设置sessionId
function setSessionId(request, response, next) {
	if (request.url !== '/set-cookie') {
		next();
		return;
	}
	response.setHeader(
		'Set-Cookie',
		'sessionId2=server2;SameSite=None;Secure;'
	);

	response.end('set success');
}
